資料視覺化¶

R 資料視覺化工具簡介

數據交點 | 郭耀仁 https://linktr.ee/yaojenkuo

In [1]:
library("RCurl")
library("dplyr")
library("ggplot2")
library("plotly")
library("rjson")
Attaching package: ‘dplyr’


The following objects are masked from ‘package:stats’:

    filter, lag


The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union



Attaching package: ‘plotly’


The following object is masked from ‘package:ggplot2’:

    last_plot


The following object is masked from ‘package:stats’:

    filter


The following object is masked from ‘package:graphics’:

    layout


(複習)視覺化被用於探索與溝通兩個場景¶

Imgur

來源:R for Data Science

(複習)載入、清理與轉換外型合稱為 "Wrangle"¶

Source: R for Data Science

R 的資料視覺化工具¶

  • "Wrangle"
    • readxl、odbc、DBI
    • dplyr
    • tidyr
  • 探索性分析與溝通分享:
    • 靜態:Base plotting system、ggplot2
    • 地理資訊、動態:Plotly

資料的載入、清理與轉換¶

(複習)常見的來源資料格式¶

  1. 純文字檔案。
  2. 試算表。
  3. 關聯式資料庫中的資料表。

使用 read.csv() 函數載入純文字檔案¶

  • 先以 RCurl::getURL() 函數下載純文字檔案。
  • 以 head(df) 檢視前五列。
In [2]:
data_url <- "https://raw.githubusercontent.com/datainpoint/classroom-data-visualization/main/data/daily_report.csv"
data <- getURL(data_url)
daily_report <- read.csv(text = data)
head(daily_report) # show the first 5 rows
A data.frame: 6 × 4
Combined_KeyLast_UpdateConfirmedDeaths
<chr><chr><int><int>
1Afghanistan2022-04-21 04:20:461785747680
2Albania 2022-04-21 04:20:462746063496
3Algeria 2022-04-21 04:20:462657466874
4Andorra 2022-04-21 04:20:46 41013 153
5Angola 2022-04-21 04:20:46 992871900
6Antarctica 2022-04-21 04:20:46 11 0
In [3]:
data_url <- "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/UID_ISO_FIPS_LookUp_Table.csv"
data <- getURL(data_url)
lookup_table <- read.csv(text = data)
head(lookup_table) # show the first 5 rows
A data.frame: 6 × 12
UIDiso2iso3code3FIPSAdmin2Province_StateCountry_RegionLatLong_Combined_KeyPopulation
<int><chr><chr><int><int><chr><chr><chr><dbl><dbl><chr><int>
1 4AFAFG 4NAAfghanistan 33.9391167.70995Afghanistan38928341
2 8ALALB 8NAAlbania 41.1533020.16830Albania 2877800
310AQATA10NAAntarctica -71.9499023.34700Antarctica NA
412DZDZA12NAAlgeria 28.03390 1.65960Algeria 43851043
520ADAND20NAAndorra 42.50630 1.52180Andorra 77265
624AOAGO24NAAngola -11.2027017.87390Angola 32866268
In [4]:
data_url <- "https://raw.githubusercontent.com/datainpoint/classroom-data-visualization/main/data/time_series.csv"
data <- getURL(data_url)
time_series <- read.csv(text = data)
head(time_series) # show the first 5 rows
A data.frame: 6 × 6
DateCountry_RegionConfirmedDeathsDaily_CasesDaily_Deaths
<chr><chr><int><int><int><int>
12020-01-22Afghanistan0000
22020-01-22Albania 0000
32020-01-22Algeria 0000
42020-01-22Andorra 0000
52020-01-22Angola 0000
62020-01-22Antarctica 0000

其他資料格式所使用的套件與函數:試算表¶

readxl::read_excel() 函數

來源:https://readxl.tidyverse.org/

其他資料格式所使用的套件與函數:關聯式資料庫中的資料表¶

  • 以 odbc 建立資料庫引擎。
  • DBI::dbConnect() 建立連線。
  • DBI::dbSendQuery() 讀取資料。

來源:https://db.rstudio.com/

(複習)資料視覺化的前置作業¶

When it comes to making graphs, half the battle occurs before you call any graphing commands.

Winston Chang

常見的資料清理、轉換技巧都能夠使用 dplyr/tidyr 的函數¶

  • 選擇欄位。
  • 篩選觀測值。
  • 排序。
  • 分組聚合。
  • 轉置。
  • 合併。
  • 連結。

資料視覺化 123¶

  1. 獲取資料。
  2. 將資料整理為合適的格式與類型。
  3. 輸入資料視覺化套件所定義好的函數。

試用 R 的資料視覺化工具¶

In [5]:
country_list <- c("US", "United Kingdom", "France", "Germany", "Canada", "Korea, South", "Japan", "Singapore", "Australia", "Taiwan", "New Zealand")
daily_report_merge_lookup_table <- inner_join(daily_report, lookup_table,
                                             by = "Combined_Key")
filtered_daily_report_merge_lookup_table <- subset(daily_report_merge_lookup_table, Country_Region %in% country_list)
data_for_bar <- filtered_daily_report_merge_lookup_table  %>% 
group_by(Country_Region) %>% 
summarise(Confirmed = sum(Confirmed)) %>% 
arrange(Confirmed)
data_for_bar
A tibble: 10 × 2
Country_RegionConfirmed
<chr><int>
New Zealand 865522
Singapore 1170970
Canada 3669173
Australia 5563493
Japan 7484263
Korea, South 16674045
United Kingdom22060704
Germany 23844536
France 28162002
US 80801162
In [6]:
data_for_line <- time_series %>% 
subset(Country_Region %in% country_list)
rownames(data_for_line) <- NULL
data_for_line[["Date"]] <- as.Date(data_for_line[["Date"]])
head(data_for_line)
A data.frame: 6 × 6
DateCountry_RegionConfirmedDeathsDaily_CasesDaily_Deaths
<date><chr><int><int><int><int>
12020-01-22Australia 0000
22020-01-22Canada 0000
32020-01-22France 0000
42020-01-22Germany 0000
52020-01-22Japan 2020
62020-01-22Korea, South1010
In [7]:
data_for_geo  <- daily_report_merge_lookup_table %>% 
group_by(iso3, Country_Region) %>% 
summarise(Confirmed = sum(Confirmed))
head(data_for_geo)
`summarise()` has grouped output by 'iso3'. You can override using the
`.groups` argument.
A grouped_df: 6 × 3
iso3Country_RegionConfirmed
<chr><chr><int>
Diamond Princess 712
MS Zaandam 9
Summer Olympics 2020 865
Winter Olympics 2022 535
ABWNetherlands 34446
AFGAfghanistan 178574

Base plotting system¶

  1. 將資料整理為合適的格式與類型。
  2. 使用 Base plotting system 的作圖函數建立主要圖形。
  3. 使用 Base plotting system 的作圖函數添加圖形元素。
In [8]:
# Plotting with base plotting system
v <- data_for_bar[["Confirmed"]]
names(v) <- data_for_bar[["Country_Region"]]
barplot(v, horiz = TRUE, las = 1, cex.names=0.5)
title(main="Confirmed By Country", xlab="Number of Confirmed")

ggplot2¶

  1. 將資料整理為合適的格式與類型。
  2. 以 library("ggplot") 載入。
  3. 使用 ggplot2 的 ggplot() 函數映射資料。
  4. 以 + 連接 ggplot2 的作圖函數建立主要圖形。
  5. 以 + 連接 ggplot2 的作圖函數添加圖形元素。
In [9]:
# Plotting with ggplot2
ggplot(data_for_line) +
geom_line(mapping = aes(x = Date, y = Confirmed, colour = Country_Region)) +
ggtitle("Cumulative Confirmed By Country")

Plotly¶

  1. 將資料整理為合適的格式與類型。
  2. 以 library("plotly") 載入。
  3. 使用 Plotly 的作圖函數建立主要圖形。
  4. 調整作圖函數的參數添加圖形元素。
In [10]:
# Plotting with Plotly
y_factor <- factor(data_for_bar[["Country_Region"]], levels=data_for_bar[["Country_Region"]])
fig <- plot_ly(x = data_for_bar[["Confirmed"]],
               y = y_factor,
               type = 'bar', orientation = 'h')
fig
In [11]:
# Plotting with Plotly
fig <- ggplot(data_for_line) +
geom_line(mapping = aes(x = Date, y = Confirmed, colour = Country_Region)) +
ggtitle("Cumulative Confirmed By Country")
ggplotly(fig)
In [12]:
# Plotting with Plotly
fig <- plot_ly(data_for_geo, type='choropleth',
               locations=data_for_geo[["iso3"]], z=data_for_geo[["Confirmed"]],
               text=data_for_geo[["Country_Region"]])
fig